<?php
/*
 * @Author: lokei
 * @Date: 2022-09-19 13:45:10
 * @LastEditors: lokei
 * @LastEditTime: 2022-11-25 08:33:30
 * @Description: 
 */
namespace App\Http\Controllers\Topic;

use App\Common\Tools\ResultTool;
use App\Http\Controllers\Controller;
use App\Models\Topic\TopicLikeModel;
use App\Models\Topic\TopicModel;
use Illuminate\Http\Request;

class LikeController extends Controller
{
	public function submit(Request $request)
	{
		$res = ResultTool::success();
		$user = app('auth')->user();
		$is_exist = TopicLikeModel::where('uid', '=', $user->uid)->where('topic_id', '=', $request->input('topic_id'))->first();
		$topic = TopicModel::where('id', '=', $request->input('topic_id'))->first();
		if(!is_null($is_exist)) {
			TopicLikeModel::where('id', '=', $is_exist->id)->delete();
			$topic->likenum = $topic->likenum > 0 ? $topic->likenum - 1 : 0;
			$res['errorMsg'] = '取消成功!';
		} else {
			$like = new TopicLikeModel();
			$like->uid = $user->uid;
			$like->topic_id = $request->input('topic_id');
			$like->created_at = date('Y-m-d H:i:s', time());
			$like->save();
			$topic->likenum = $topic->likenum + 1;
			$res['errorMsg'] = '点赞成功!';
		}
		$topic->save();
		return $res;
	}

	public function ofTopics(Request $request) {
		$user = app('auth')->user();
		$ids = json_decode($request->input('ids'));
		$items = TopicLikeModel::where('uid', '=', $user->uid)->whereIn('topic_id', $ids)->get();
		$res = ResultTool::success();
		$res['data']['items'] = $items;
		return $res;
	}
}
